/** @description  请求辅助类**/
/** @author  wutao **/
/** @date 2020-04-20 **/
import storage from "../storage/index";
import appApi from "../../appApi.js"
// import dbUtils from "../dbutils/index"
//由于接口较多没有统一使用加载接口是否loading  所以另行单独配置不需要loading api
let ApiData = ['/yilimz/app/weather/queryWeatherfromlocation','/yilimz/app/subscript/get','/yilimz/app/jobMessage/selectCountByDay']
let noLoadingApi = []
ApiData.forEach(item=>{
	noLoadingApi.push(appApi.baseUrl[appApi.server]+item)
})

let request = {}
let loadingCount = 0
//普通请求
request.request = (opt, callback, errorcallback, isloading = false) => {
	let tmpOpt = JSON.parse(JSON.stringify(opt));
	//判断是否有网络 
	request.isNetworkOnline().then(res => {
		if (res) {
			request.handleError(-1001, '暂无网络', errorcallback);
			return null;
		}

		let opts = {};
		opts['timeout'] = 15000;
		opts = Object.assign(opts, tmpOpt);
		console.log(opts)
		if(noLoadingApi.indexOf(opts.url) != -1){
			isloading = false;
		}else{
			//全局加loading
			isloading = true;
		}
		if (isloading) {
			if (loadingCount == 0) {
				uni.showLoading({
					mask: true
				});
			}
			loadingCount++
		}
		//请求开始时间
		let startTime = new Date().getTime();

		//成功
		opts.success = (res) => {
			console.log('======= 请求成功')
			console.log(res);

			// if (res.statusCode == 20000) {
				let data = res.data;
				if (data.code == 20000) {
					if (data.total || data.total == 0) {
						callback(data.rows, data.total)
					} else {
						callback(data.data)
					}


				} else if (data.code == 1) {
					errorcallback(data.code, data.msg, errorcallback);
				} else {
					request.handleError(data.code, data.msg, errorcallback);
				}
			// } else {
			// 	request.handleError(res.statusCode, res.data.msg, errorcallback);
			// }
		};
		//失败
		opts.fail = (res) => {

			console.log('======= 请求失败', res)

			if (opt.url == 'https://spms.lpht.com.cn/hubsales/apisSales/requestStatic') {
				return
			}
			request.handleError(res.statusCode, res.msg, errorcallback);

		};
		//结束
		opts.complete = (res) => {
			// console.log('======= 请求结束')
			// console.log(res);
			if (isloading) {
				loadingCount--
				if (loadingCount == 0) {
					uni.hideLoading();
				}
			}
		}
		return uni.request(opts);
	});



}
//上传图片
request.uploadImg = (opt, params, formData, callback, errorcallback) => {
	console.log("上传图片：", opt)
	console.log("上传图片：", params)
	if (loadingCount == 0) {
		uni.showLoading({
			title: '上传中...',
			mask: true
		});
	}
	loadingCount++
	uni.uploadFile({
		url: opt.url,
		filePath: params,
		header: {
			'Authorization': storage.getToken() || ''
		},
		formData: formData || {},
		name: opt.name || 'file',
		success: (res) => {
			console.log(res);
			loadingCount--
			if (loadingCount == 0) {
				uni.hideLoading();
			}
			if (res.statusCode == 20000) {
				callback && callback(res.data)
			} else {
				errorcallback && errorcallback(res)
			}

		},
		fail: (err) => {
			console.log(err)
			loadingCount--
			if (loadingCount == 0) {
				uni.hideLoading();
			}
			errorcallback && errorcallback(err)
		}
	});
	return
}
//上传视频
request.uploadMp4 = (params, callback, errorcallback) => {
	console.log("上传视频：", appApi.baseUrl[appApi.server] + 'asyncUpload')
	console.log("上传视频：", params)
	if (loadingCount == 0) {
		uni.showLoading({
			title: 'Loading...',
			mask: true
		});
	}
	loadingCount++
	uni.uploadFile({
		url: appApi.baseUrl[appApi.server] + 'asyncUpload',
		filePath: params,
		header: {
			'Authorization': storage.getToken() || ''
		},
		name: 'file',
		success: (res) => {
			loadingCount--
			if (loadingCount == 0) {
				uni.hideLoading();
			}
			callback(res.data)
		},
		fail: (err) => {
			console.log(err)
			loadingCount--
			if (loadingCount == 0) {
				uni.hideLoading();
			}
		}
	});
	return
}
//下载文件
request.downloadFile = (showLoading = true, downloadUrl, callback, errorcallback) => {
	let opts = {};
	opts.url = downloadUrl;

	opts.success = (res) => {
		if (res.statusCode == 20000) {
			callback(res.tempFilePath)
		}
	}
	//失败
	opts.fail = (res) => {
		console.log('======= xiazai失败')
		console.log(res);
		let code = res.errMsg;
		errorcallback(code)
	};
	//结束
	opts.complete = (res) => {
		console.log('======= xiazai结束')
		console.log(res);
		if (showLoading) {
			uni.hideLoading();
		}

	}
	if (showLoading) {
		uni.showLoading({
			title: '上传中...',
			mask: true

		});
	}

	// downloadTask.onProgressUpdate((res) => {
	// 	onProgressUpdate(res);
	// })
	return uni.downloadFile(opts);
}
//错误吗处理
request.handleError = (errorCode, errorMsg, errorCallback) => {
	console.log(errorCode, errorMsg, errorCallback)
	let msg = errorMsg || '账号或者密码不存在'
	if (errorCode == -1001) {
		//网络异常
		if (msg != "") {
			uni.showToast({
				title: msg,
				position: 'bottom',
				duration: 2000
			})
		}
	} else if (errorCode == 400) {
		if (msg != "") {
			uni.showToast({
				title: msg,
				position: 'bottom',
				duration: 2000
			})
		}
	} else if (errorCode == 404) {
		if (msg != "") {
			uni.showToast({
				title: msg,
				position: 'bottom',
				duration: 2000
			})
		}
		//请求资源不存在
	} else if (errorCode == 408) {
		if (msg != "") {
			uni.showToast({
				title: msg,
				position: 'bottom',
				duration: 2000
			})
		}
		//请求超时
	} else if (errorCode == 500) {
		if (msg.indexOf("登录信息已失效，请重新登录") != -1|| msg.indexOf("token已经失效") != -1 || msg.indexOf("令牌不能为空") != -1 || msg.indexOf("登录状态已过期") != -1 || msg
			.indexOf("令牌验证失败") != -1) {
			//token无效 删除 token  用户  分销商信息
			storage.removeToken();
			storage.removeUserInfo();
			console.log(`清空缓存到登录页面`)
			uni.$emit('re-login', {});
		} else {
			if (msg != "") {
				uni.showToast({
					title: msg,
					position: 'bottom',
					duration: 2000,
					icon: 'none'
				})
			}
		}
		//请求异常
	} else {
		//其他异常
		if (msg != "") {
			//天气接口异常不抛出
			if (msg.indexOf("qryweather.market.alicloudapi.com") == -1) {
				uni.showToast({
					title: msg,
					position: 'bottom',
					duration: 2000
				})
			}
		}
	}
	if (errorCallback) {
		errorCallback(errorCode, msg)
		console.log("错误码=============", errorCode, msg)
	}

}

//判断网络状态
request.isNetworkOnline = () => {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success: (res) => {
				let online = res.networkType == 'none'
				resolve(online);
			}
		})
	});

}


export default request
